package com.simplegui.examples.ricerocks;

import static com.simplegui.examples.ricerocks.RiceRocksConfigurations.*;

import java.awt.Point;

import com.simplegui.api.Canvas;
import com.simplegui.api.GameComponent;
import com.simplegui.api.ImageFile;
import com.simplegui.api.ImageInfo;
import com.simplegui.api.util.MathUtils;

public class Ship implements GameComponent{

	private RiceRocks riceRocks;
	private Double[] pos;
	private Double[] vel;
	private boolean thrust;
	private double angle;
	private double angle_vel;
	private ImageInfo imageInfo;
	private ImageFile imageFile;

	public Ship(RiceRocks riceRocks, Double[] pos, boolean thrust, double angle, double angle_vel) {
		super();
		this.riceRocks = riceRocks;
		this.pos = pos;
		this.vel = new Double[]{0d,0d};
		this.thrust = thrust;
		this.angle = angle;
		this.angle_vel = angle_vel;
		this.imageInfo = ship_info;
		this.imageFile = ship_image;
	}

	@Override
	public void executeLogic() {
        // update angle
        angle += angle_vel;
        
        // update position
        pos[0] = (pos[0] + vel[0]) % WIDTH;
        pos[1] = (pos[1] + vel[1]) % HEIGHT;
        
        // update velocity
        if (thrust){
        	Double[] acc = MathUtils.angle_to_vector(angle);
        	vel[0] += acc[0] * .1;
        	vel[1] += acc[1] * .1;
        }
            
        vel[0] *= .99;
        vel[1] *= .99;
	}

	@Override
	public void draw(Canvas canvas) {
        if (thrust){
        	canvas.drawImage(imageFile, new Point(imageInfo.getCenter().x + imageInfo.getSize().width, imageInfo.getCenter().y) , imageInfo.getSize(), getPosition(), imageInfo.getSize(), angle);
        } else {
        	canvas.drawImage(imageFile, imageInfo.getCenter(), imageInfo.getSize(), getPosition(), imageInfo.getSize(), angle);
        }
		
	}
	
	public void setThrust(boolean thrust) {
		this.thrust = thrust;
		if (thrust){
			ship_thrust_sound.rewind();
			ship_thrust_sound.play();
		}else{
			ship_thrust_sound.pause();
		}
	}
	
	public void incrementAngleVel(){
		angle_vel += 0.05;
	}
	
	public void decrementAngleVel(){
		angle_vel -= 0.05;
	}
	
	public void shoot(){
		Double[] forward = MathUtils.angle_to_vector(angle);
		Double[] missile_pos = {pos[0] + imageInfo.getRadius() * forward[0], pos[1] + imageInfo.getRadius() * forward[1]};
		Double[] missile_vel = {vel[0] + 6 * forward[0], vel[1] + 6 * forward[1]};
		Sprite a_missile = new Sprite(missile_pos, missile_vel, angle, 0d, missile_info, missile_image, missile_sound);
		riceRocks.addExtraGameComponent(a_missile);
	}
	    
	@Override
	public Point getPosition() {
		return new Point(pos[0].intValue(), pos[1].intValue());
	}


	@Override
	public double getRadius() {
		return imageInfo.getRadius();
	}


}
